﻿using BaseBll;
using BaseWebApi.App_Start;
using BaseWebApi.Common;
using BaseWebApi.Models;
using Common;
using Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Http;

namespace BaseWebApi.Controllers
{
    /// <summary>
    /// 人员管理
    /// </summary>
    [ControllerGroup(groupName: "Staff", useage: "资产维护-人员管理")]
    public class StaffController : BaseController
    {
        private JWTPlayloadInfo playload;

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">页尺寸</param>
        /// <param name="name">人员姓名</param>
        /// <param name="postName">岗位名称</param>
        /// <param name="gender">性别</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetPageList(int pageIndex, int pageSize, string name = "", string postName = "", int gender = 0)
        {
            string strWhere = "";
            if (!string.IsNullOrEmpty(name))
            {
                strWhere += " and t1.Name like '%" + name + "%'";
            }
            if (!string.IsNullOrEmpty(postName))
            {
                strWhere += " and t2.PostName like '%" + postName + "%'";
            }
            if (gender != 0)
            {
                strWhere += " and t1.Gender = " + gender;
            }

            DataTable dt = StaffBll.Instance.GetPageList(pageSize, pageIndex, strWhere, "t1.CreateTime DESC", out int records);
            int totalPages = PageHelper.GetPageCount(pageSize, records);
            return JsonHelper.SuccessJson(CommonOperation.DataTable2JArray(dt), pageIndex, totalPages, records);
        }

        /// <summary>
        /// 查询人员列表
        /// </summary>
        /// <param name="name">姓名（默认""）</param>
        /// <param name="postName">岗位名称（默认""）</param>
        /// <param name="gender">性别（默认0）</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetList(string name = "", string postName = "", int gender = 0)
        {
            string strWhere = "";
            if (!string.IsNullOrEmpty(name))
            {
                strWhere += " and t1.Name like '%" + name + "%'";
            }
            if (!string.IsNullOrEmpty(postName))
            {
                strWhere += " and t2.PostName like '%" + postName + "%'";
            }
            if (gender != 0)
            {
                strWhere += " and t1.Gender = " + gender;
            }

            List<Staff> list = StaffBll.Instance.GetList(strWhere);

            return JsonHelper.SuccessJson(JsonHelper.ListToJArray(list));
        }

        /// <summary>
        /// 根据ID获取实体对象
        /// </summary>
        /// <param name="ID">数据表ID</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetModel(int ID)
        {
            if (ID > 0)
            {
                Staff model = StaffBll.Instance.GetModelById(ID);
                if (model != null)
                {
                    // 查询文件
                    DataTable dt = UploadBll.Instance.GetFiles(ID, "Staff");
                    model.ImgList = CommonOperation.ConvertDataTableToModelList<FileData>(dt);
                    return JsonHelper.SuccessJson(JsonHelper.ModelToJObject(model));
                }
                else
                {
                    return JsonHelper.FailJson("数据不存在");
                }
            }
            else
            {
                return JsonHelper.FailJson("参数错误");
            }
        }

        /// <summary>
        /// 根据人员id查询文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetFileById(int id)
        {
            if (id <= 0)
            {
                return JsonHelper.ErrorJson("参数错误");
            }
            DataTable dt = UploadBll.Instance.GetFiles(id, "Staff");
            return JsonHelper.SuccessJson(CommonOperation.DataTable2JArray(dt));
        }

        /// <summary>
        /// 新增人员
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage AddStaff([FromBody] Staff model)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                //验证各字段合法性
                string msg = "";
                bool isOk = StaffBll.Instance.VerifyModel(model, ref msg);
                if (isOk)
                {
                    //默认字段
                    model.CreateTime = DateTime.Now;
                    model.CreateUser = playload.UserName;
                    bool res = StaffBll.Instance.AddStaff(model);
                    if (res)
                    {
                        // 更新文件信息
                        if (model.ImgList != null && model.ImgList.Count > 0)
                        {
                            UploadBll.Instance.Update(model.ID, model.ImgList);
                        }
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Staff, "新增人员", Constant.ActionEnum.Add, Constant.StatusEnum.Success));
                        return JsonHelper.SuccessJson("新增成功");
                    }
                    else
                    {
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Staff, "新增人员", Constant.ActionEnum.Add, Constant.StatusEnum.Fail));
                        return JsonHelper.FailJson("新增失败");
                    }
                }
                else
                {
                    return JsonHelper.FailJson(msg);
                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Staff, "新增人员:" + ex.Message, Constant.ActionEnum.Add, Constant.StatusEnum.Exception), ex);
                throw ex;
            }
        }

        /// <summary>
        /// 修改人员
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage UpdateStaff([FromBody] Staff model)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            if (model.ID <= 0)
            {
                return JsonHelper.ErrorJson("参数错误");
            }
            try
            {
                bool isExist = StaffBll.Instance.IsExist(" and ID=" + model.ID);
                if (!isExist)
                {
                    return JsonHelper.ErrorJson("不存在该数据");
                }
                //验证各字段合法性
                string msg = "";
                bool isOk = StaffBll.Instance.VerifyModel(model, ref msg);
                if (isOk)
                {
                    //默认字段
                    model.UpdateTime = DateTime.Now;
                    model.UpdateUser = playload.UserName;
                    bool res = StaffBll.Instance.UpdateStaff(model);
                    if (res)
                    {                      
                        // 更新文件信息
                        if (model.ImgList != null && model.ImgList.Count > 0)
                        {
                            UploadBll.Instance.Update(model.ID, model.ImgList);
                        }
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Staff, "修改人员", Constant.ActionEnum.Edit, Constant.StatusEnum.Success));
                        return JsonHelper.SuccessJson("修改成功");
                    }
                    else
                    {
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Staff, "修改人员", Constant.ActionEnum.Edit, Constant.StatusEnum.Fail));
                        return JsonHelper.FailJson("修改失败");
                    }
                }
                else
                {
                    return JsonHelper.FailJson(msg);
                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Staff, "修改人员:" + ex.Message, Constant.ActionEnum.Edit, Constant.StatusEnum.Exception), ex);
                throw ex;
            }
        }

        /// <summary>
        /// 删除人员
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DeleteStaff(int id)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            if (id <= 0)
            {
                return JsonHelper.ErrorJson("参数错误");
            }
            try
            {
                bool isExist = StaffBll.Instance.IsExist(" and ID=" + id);
                if (!isExist)
                {
                    return JsonHelper.ErrorJson("不存在该数据");
                }
                bool result;
                // 先删除相关图片
                DataTable dt = UploadBll.Instance.GetFiles(id, "Staff");
                if (dt.Rows.Count > 0)
                {
                    List<FileData> files = CommonOperation.ConvertDataTableToModelList<FileData>(dt);
                    string fid = "";
                    for (int i = 0; i < files.Count; i++)
                    {
                        if (string.IsNullOrEmpty(fid))
                        {
                            fid = "'" + files[i].RelationId + "'";
                        }
                        else
                        {
                            fid += ",'" + files[i].RelationId + "'";
                        }
                    }
                    bool res = UploadBll.Instance.DeleteFiles(fid, "Staff", files);
                    if (res)
                    {
                        result = StaffBll.Instance.DeleteStaff(id.ToString(), playload.UserName);
                        if (result)
                        {
                            new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Staff, "删除人员", Constant.ActionEnum.Delete, Constant.StatusEnum.Success));
                            return JsonHelper.SuccessJson("删除成功");
                        }
                        else
                        {
                            new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Staff, "删除人员", Constant.ActionEnum.Delete, Constant.StatusEnum.Fail));
                            return JsonHelper.SuccessJson("删除失败");
                        }
                    }
                    else
                    {
                        return JsonHelper.FailJson("删除文件失败");
                    }
                }
                else
                {
                    result = StaffBll.Instance.DeleteStaff(id.ToString(), playload.UserName);
                    if (result)
                    {
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Staff, "删除人员", Constant.ActionEnum.Delete, Constant.StatusEnum.Success));
                        return JsonHelper.SuccessJson("删除成功");
                    }
                    else
                    {
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Staff, "删除人员", Constant.ActionEnum.Delete, Constant.StatusEnum.Fail));
                        return JsonHelper.SuccessJson("删除失败");
                    }
                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Staff, "删除人员:" + ex.Message, Constant.ActionEnum.Delete, Constant.StatusEnum.Exception), ex);
                throw ex;
            }
        }

        #region 上传文件相关

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage UploadPic()
        {
            JWTPlayloadInfo playload = (JWTPlayloadInfo)Request.Properties["playload"];

            List<FileData> list = new List<FileData>();
            HttpFileCollection files = HttpContext.Current.Request.Files;
            FileData model = null;
            foreach (var key in files.AllKeys)
            {
                HttpPostedFile postedFile = files[key];
                if (!string.IsNullOrEmpty(postedFile.FileName))
                {
                    // file.SaveAs(HttpContext.Current.Server.MapPath("~/imgcoll/") + file.FileName);
                    //文件扩展名，不含“.”
                    string fileExt = Utils.GetFileExt(postedFile.FileName);

                    // 图片类型
                    Regex regex = new Regex(@"gif|jpg|jpeg|png|bmp|webp");
                    bool isMatch = regex.IsMatch(fileExt);
                    if (!isMatch)
                    {
                        return JsonHelper.ErrorJson("文件类型不匹配");
                    }

                    model = UploadHelper.SaveFilePic(postedFile, UploadHelper.uploadPath + "images/pc/staff/" + DateTime.Now.ToString("yyyyMMdd"), DateTime.Now.ToString("yyyyMMddHHmmss"));

                    // 文件类型
                    model.FileType = fileExt;

                    // 关联表
                    model.RelationTable = "Staff";

                    if (model != null)
                    {
                        list.Add(model);
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            if (list.Count > 0)
            {
                bool result = UploadBll.Instance.AddList(list);
                if (result)
                {
                    new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Staff, "上传图片(relationTable:" + model.RelationTable + ")", Constant.ActionEnum.Upload, Constant.StatusEnum.Success));
                    return JsonHelper.SuccessJson(JsonHelper.ListToJArray(list));
                }
                else
                {
                    return JsonHelper.ErrorJson("上传失败，稍后重试");
                }
            }
            else
            {
                return JsonHelper.ErrorJson("没有匹配的文件类型");
            }
        }

        /// <summary>
        /// 根据文件ID删除文件
        /// </summary>
        /// <param name="fileID">文件ID</param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DeletePic(string fileID)
        {
            JWTPlayloadInfo playload = (JWTPlayloadInfo)Request.Properties["playload"];
            if (string.IsNullOrEmpty(fileID))
            {
                return JsonHelper.ErrorJson("参数错误");
            }
            FileData model = UploadBll.Instance.GetFileByID(fileID);
            if (model != null)
            {
                bool res = UploadBll.Instance.DeleteFilesByID(fileID, model);
                if (res)
                {
                    new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Staff, "删除文件(ID:" + fileID + ")", Constant.ActionEnum.Delete, Constant.StatusEnum.Success));
                    return JsonHelper.SuccessJson("删除成功！");
                }
                else
                {
                    return JsonHelper.FailJson("删除失败！");
                }
            }
            else
            {
                return JsonHelper.FailJson("参数错误！");
            }
        }

        #endregion 上传文件相关
    }
}